<?php
/**
 * @todo 登录
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/12/22
 * Time: 11:05
 */
namespace app\web\service;

use app\web\model\Shop;
use app\web\model\ShopConfig;
use app\web\util\AlibabaUtil;
use app\common\util\JwtUtil;
use think\facade\Log;

class LoginService{
    /**
     * @todo 登录授权
     * @author ZJF
     */
    public function login($code = ''){
        if(empty($code)){
            return array_response([],1,'无效的授权码');
        }
        try{
            //根据授权码换取token
            $ali_util = new AlibabaUtil();
            $res = $ali_util->creatAccessToken($code);
            if($res['code']!=0){
                return $res;
            }
            $ali_res = $res['data'];
            $shop_model = new Shop();
            $shop_info = $shop_model
                ->where("ali_id='{$ali_res['aliId']}' AND is_del=0")
                ->find();
            $now_time = date('Y-m-d H:i:s');
            $access_timeout = bcadd(time(),bcsub($ali_res['expires_in'],60));
            $refresh_timeout = strtotime(substr($ali_res['refresh_token_timeout'],0,14));
            $shop_data = array(
                'ali_id'=>$ali_res['aliId'],
                'login_id'=>$ali_res['resource_owner'],
                'member_id'=>$ali_res['memberId'],
                'access_token'=>$ali_res['access_token'],
                'expires_timeout'=>$access_timeout,
                'refresh_token'=>$ali_res['refresh_token'],
                'refresh_token_timeout'=>$refresh_timeout,
                'mtime'=>$now_time
            );
            //根据ali_id判断是否存在
            if(empty($shop_info)){
                //不存在新增
                $shop_data['pid'] = $ali_res['aliId'];
                $shop_data['ctime'] = $now_time;
                $id = $shop_model->insert($shop_data,true);
                if(false===$id){
                    //失败
                    return array_response([],1,'新增授权失败');
                }
                //无配置信息，新增
                $config_data = array(
                    'shop_id'=>$id,
                    'order_sort'=>2,
                    'express_sort'=>1,
                    'invoice_sort'=>1,
                    'filter'=>0,
                    'ctime'=>$now_time,
                    'mtime'=>$now_time
                );
                $config_model = new ShopConfig();
                $res = $config_model->insert($config_data);
            }
            else{
                //存在更新，token、ref_token
                $id = $shop_info['id'];
                //已存在修改
                $res = $shop_model->where("id='{$id}'")->save($shop_data);
                if(false===$res){
                    //失败
                    return array_response([],1,'授权更新失败');
                }
            }
            //生成令牌
            $payload['shop_id'] = $id;
            $token = think_encrypt(JwtUtil::encode($payload), '', 24*60*60);
            return array_response(array('token'=>$token));
        }
        catch (\Exception $e){
            $error = array(
                'message'=>$e->getMessage(),
                'url'=>$e->getFile(),
                'code'=>$e->getCode(),
                'line'=>$e->getLine()
            );
            Log::write(json_encode($error,JSON_UNESCAPED_UNICODE),"ERROR");
            return array_response([],1,"异常错误");
        }
    }
}